//
//  TKConverseViewController.m
//  TKIM
//
//  Created by liupm on 15/10/28.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMConverseViewController.h"
#import "TKIMConverseView.h"
#import "TKIMHelper.h"
#import "TKFriendListSetViewController.h"
#import "TKIMSMSChatViewController.h"
#import "TKIMConverseServiceView.h"
#import "TKFriendListSetViewController.h"
//#import "TKIMOfficalDetailViewController.h"
#import "EBMWebViewViewController.h"


@interface TKIMConverseViewController ()<TKIMManagerDelegate,TKIMConverseViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong) TKIMConverseView *converseView;
@property(nonatomic,strong) UITapGestureRecognizer *loginTap;
@property(nonatomic,strong) TKIMConverseMessage *serviceCov;//客服账号
@property(nonatomic,strong) TKIMConverseServiceView * serviceView;
@property(nonatomic,strong) UIAlertView *pushAlertView;
@end

@implementation TKIMConverseViewController
{
    dispatch_queue_t updateQueue;
}


-(void)loadView
{
    [super loadView];
    self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showData) name:@"Converse_Change" object:nil];
    
    updateQueue = dispatch_queue_create("TKIMConverseViewQueue", nil);
    
    self.view.backgroundColor = [UIColor whiteColor];    
    self.navigationItem.title = @"消息中心";
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
    temporaryBarButtonItem.title =@"";
//    self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
//    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    
    //设置返回样式图片
    UIImage *image = TKIMGetImage(@"btn_back@2x");
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    self.navigationController.navigationBar.backIndicatorImage = image;
//    self.navigationController.navigationBar.backIndicatorTransitionMaskImage = image;

    UIButton* btn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
    [btn addTarget:self action:@selector(goFriendSet:) forControlEvents:UIControlEventTouchUpInside];
    [btn setImage:TKIMGetImage(@"icon-setting@2x") forState:UIControlStateNormal];
    btn.tintColor=[UIColor whiteColor];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    UIBarButtonItem* rightBar=[[UIBarButtonItem alloc] initWithCustomView:btn];
//    self.navigationItem.rightBarButtonItem=rightBar;
    
    UIButton* back=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 90, 44)];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [back setImage:TKIMGetImage(@"btn_back") forState:UIControlStateNormal];
    back.tintColor=[UIColor whiteColor];
    back.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithCustomView:back];
//    self.navigationItem.leftBarButtonItem=leftBar;
    
    CGRect rectOfStatusbar = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectOfNavigationbar = self.navigationController.navigationBar.frame;

    
    if ([TKHttpService sharedInstance].transUser) {
        _converseView = [[TKIMConverseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-rectOfStatusbar.size.height-rectOfNavigationbar.size.height-HOME_INDICATOR_HEIGHT) withDelegate:self contentsController:self];
        [self.view addSubview:_converseView];
//        [self.view addSubview:self.serviceView];
    }else{
       _converseView = [[TKIMConverseView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-rectOfStatusbar.size.height-rectOfNavigationbar.size.height-HOME_INDICATOR_HEIGHT) withDelegate:self contentsController:self];
        [self.view addSubview:_converseView];
    }
}


-(void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"TKIMConverseView_headerRefresh" object:nil];
    
    NSString *previousStr = [[NSUserDefaults standardUserDefaults]objectForKey:@"kTKIMPushAlertDate"];
    CGFloat previousFloat = [previousStr floatValue];
    
    NSString *currentStr = [self currentTimeStr];
    CGFloat currentFloat = [currentStr floatValue];
    
    CGFloat timeInterval = currentFloat - previousFloat;
    CGFloat weekInterval = 7*24*60*60;
    BOOL needAlert = NO;
    if (timeInterval > weekInterval) {
        needAlert = YES;
    }
    
    BOOL notificationEnable = [self isUserNotificationEnable];
    if (!notificationEnable && needAlert) {
        NSLog(@"不允许推送");
        self.pushAlertView = [[UIAlertView alloc] initWithTitle:@"开启消息推送" message:@"开启推送，第一时间收到智能盯盘、每日快讯、重要公告等重要提醒" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"立即开启", nil];
        self.pushAlertView.delegate = self;
        [self.pushAlertView show];
        
        
        [[NSUserDefaults standardUserDefaults] setObject:currentStr forKey:@"kTKIMPushAlertDate"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView == self.pushAlertView) {
        if (buttonIndex == 1) {
            [self goToAppSystemSetting];
        }
    }
}

- (BOOL)isUserNotificationEnable { // 判断用户是否允许接收通知
    BOOL isEnable = NO;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0f) { // iOS版本 >=8.0 处理逻辑
        UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
        isEnable = (UIUserNotificationTypeNone == setting.types) ? NO : YES;
    } else { // iOS版本 <8.0 处理逻辑
        UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        isEnable = (UIRemoteNotificationTypeNone == type) ? NO : YES;
    }
    return isEnable;
}

// 如果用户关闭了接收通知功能，该方法可以跳转到APP设置页面进行修改  iOS版本 >=8.0 处理逻辑
- (void)goToAppSystemSetting {
    UIApplication *application = [UIApplication sharedApplication];
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if ([application canOpenURL:url]) {
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:url options:@{} completionHandler:nil];
        } else {
            [application openURL:url];
        }
    }
}

//获取当前时间戳
- (NSString *)currentTimeStr{
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];//获取当前时间0秒后的时间
    NSTimeInterval time =  [date timeIntervalSince1970];
    NSString *timeString = [NSString stringWithFormat:@"%.0f", time];
    return timeString;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear: animated];    
    //#warning 防止重复监听
    [[TKIMManager shareInstance] unRegisterDelegate:self];
    //#warning 注册代理监听
    [[TKIMManager shareInstance] registerDelegate:self];
    [_converseView reloadHead:@""];
    [_converseView    removeGestureRecognizer:_loginTap];
    [self showData];
    
    //请求中间帐号
    [self loadTransferUser];
}


- (void)loadTransferUser
{
    CGRect rectOfStatusbar = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectOfNavigationbar = self.navigationController.navigationBar.frame;
    [TKIMSDKManager getCoustomeCommonService:^(TKIMResultVo *resultVo) {
        if (resultVo.errorNo == 0) {
            if ([TKHttpService sharedInstance].transUser) {
                if (!self.serviceView.superview) {
//                    [self.view addSubview:self.serviceView];
                }
                _converseView.height = TKIMScreenHeight-rectOfStatusbar.size.height-rectOfNavigationbar.size.height-HOME_INDICATOR_HEIGHT;
                self.serviceView.top = CGRectGetMaxY(self.converseView.frame);
            }else{
                if (self.serviceView.superview) {
                    [self.serviceView removeFromSuperview];
                }
                _converseView.height = self.view.frame.size.height-rectOfStatusbar.size.height-rectOfNavigationbar.size.height-HOME_INDICATOR_HEIGHT;
            }
        }
    }];
}


-(void)back
{
    [[NSNotificationCenter defaultCenter] postNotificationName:TKIMSDK_BACK_ACTION object:nil];
}


-(void)refreshData
{
//  __weak __typeof(self) weakSelf=self;
//  [TKIMSDKManager loadConversationsWithCountFromServer:^(NSInteger errorNumber, NSString *info) {
//  __strong __typeof(self)strongSelf =weakSelf;
    [self showData];
//    }];
}

-(void)showData{
    NSMutableArray *array = [[TKIMManager shareInstance] queryHisConverses];
    [self didReceiveConverse:array];
}


-(void)setViewDataInfo:(NSDictionary *)viewDataInfo{
    [super setViewDataInfo:viewDataInfo];
    if (viewDataInfo) {
        [self doNotisAction:viewDataInfo];
    }
}


-(void)doNotisAction:(NSDictionary*)dict{

    if (dict) {//不为空就需要处理
        NSString*actionType=dict[@"stateActionType"];
        if (actionType&&actionType.length) {
            if ([actionType isEqualToString:@"url"]) {
                 NSString* actionVaule=dict[@"stateActionValue"];
                if (actionVaule&&actionVaule.length) {
                    
                    NSDictionary* dict2=[TKDataHelper jsonToDictionary:actionVaule];
                    
                if (dict2) {
                    NSString* url=dict2[@"url"];
                    NSString* title=dict2[@"title"];
                    
                    NSString *dotType = dict[@"stateTopic"];
                    [_converseView cleanRedDot:dotType];
                    
                    if (url&&url.length>0) {
                        /*
                        TKIMOfficalDetailViewController *detail = [[TKIMOfficalDetailViewController alloc] init];
                        TKIMSrvRichItem * item=[[TKIMSrvRichItem alloc] init];
                        item.url=url;
                        detail.item =item;
                        detail.navtitle=title;
                        [self.navigationController pushViewController:detail animated:YES];
                         */
                        
                        EBMWebViewViewController *webView = [[EBMWebViewViewController alloc]initWithUrlString:url titleString:title];
                        [self.navigationController pushViewController:webView animated:YES];
                        
                    }
                }
                }

            }else if ([actionType isEqualToString:@"activity"]){//打开页面
                [self doNotisNavAction:dict];
            }else if ([actionType isEqualToString:@"custom"]){
             [[NSNotificationCenter defaultCenter] postNotificationName:MESSAGE_ITEM_CLICK object:nil userInfo:(id)dict]; //暂时性处
            }else if ([actionType isEqualToString:@"app"]){
                 [self doNotisNavAction:dict];
            }
        }
    }
}


//跳转原生页面
-(void)doNotisNavAction:(NSDictionary*)vaule
{
    NSString* actionVaule=vaule[@"stateActionValue"];
    if (actionVaule&&actionVaule.length) {
        NSDictionary* dict=[TKDataHelper jsonToDictionary:actionVaule];
        if (dict) {
            NSString* pageview_type=dict[@"ios"];
            if ([@"mainList" isEqualToString:pageview_type]) {
                
                NSString* jid=dict[@"jid"];
                if (jid&&jid.length>0) {

                    TKIMConverseMessage* cov=[[TKIMConverseMessage alloc] init];
                    cov.channel=2;
                    TKIMUser* user=[[TKIMUser alloc] init];
                    user.jid=jid;
                    user.userID=jid;
                    user.userName=[[TKIMDBManager shareInstance]queryTargetNameById:jid];
                    [self toChat:user converse:cov];
                }
                
            }else if ([@"settingList" isEqualToString:pageview_type]){
                [self goFriendSet:nil];
            }
        }
    }
}

//跳转控制器
-(void)doNotisActivity:(NSDictionary*)vaule{


}

-(void)goFriendSet:(UIButton*)btn{
    TKFriendListSetViewController *friendlistset=[[TKFriendListSetViewController alloc] init];
    friendlistset.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:friendlistset animated:YES];
}


/**
 *  @Author lpm, 15-12-21 14:12:51
 *
 *  @brief
 *
 *  @param alertView
 *  @param buttonIndex
 */
- (void)toLogin
{
        //发送未登录通知
    [[NSNotificationCenter defaultCenter] postNotificationName:TKIMNotLoginNotification object:nil];
}


#pragma mark 监听代理（更多代理可在TKIMManagerDelegate中查看）
//#warning 特别注意以下为im代理监听，必须注册为监听代理才会被调用

/**
 *  @Author lpm, 15-09-17 17:09:37
 *
 *  @brief  连接成功
 *
 *  @param xmppStream
 */
-(void)didReceiveServerStatus:(TKIMStatus *)status
{
    switch (status.statusCode)
    {
        case TKIMLoginSuccess:
        {
            [_converseView reloadHead:@""];
            NSMutableArray *array = [[TKIMManager shareInstance] queryHisConverses];
            [self didReceiveConverse:array];
            
            NSMutableDictionary * dict=[[NSMutableDictionary alloc] init];
            [dict setObject:@"customer" forKey:@"role"];
            [[TKIMManager shareInstance] loadConversationsWithCountFromServer:dict callBack:^(TKIMResultVo *resultVo) {
//                NSLog(@"%@",resultVo.errorInfo);
            }];
            
        }
            break;
        case TKIMConnectUnReachable:
        case TKIMServerError:
        case TKIMDisConnect:
        {
            [_converseView reloadHead:status.statusInfo];
        }
            break;
        default:
            break;
    }
}


/**
 *  @Author lpm, 15-10-30 17:10:55
 *
 *  @brief  收到会话列表
 *
 *  @param converses
 */
-(void)didReceiveConverse:(NSMutableArray *)conversess
{
    

    __weak __typeof(self) weakSelf = self;
    dispatch_barrier_async(updateQueue, ^{
        
        
        
        NSMutableArray*converses=[[NSMutableArray alloc] initWithArray:conversess];
        
        NSArray * data = [TKIMCacheHelper valueForKey:SDK_PUSHITEMNOSHOWDATALISTJID];
        if(data&&data.count){
            NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (targetUser IN %@)",data];
            NSArray * conversestemp =   [converses filteredArrayUsingPredicate:filterPredicate];
            converses=[[NSMutableArray alloc] initWithArray:conversestemp];
        }
        
        NSArray * data2 = [TKIMCacheHelper valueForKey:SDK_CUSTOMERITEMNOSHOWDATALISTJID];
        if(data2&&data2.count){
            NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (targetUser IN %@)",data2];
            NSArray * conversestemp =   [converses filteredArrayUsingPredicate:filterPredicate];
            converses=[[NSMutableArray alloc] initWithArray:conversestemp];
        }
        NSString* apptype =[TKHttpService app_type];
        
        
        __strong __typeof(weakSelf) strongSelf = self;
        for (TKIMConverseMessage *msg in converses)
        {
            if([@"customer" isEqualToString:apptype]&& msg.channel == 1){
                _serviceCov = msg;
            }
            if (msg.type == TKIMMsgTypeTxt)
            {
                msg.text = [TKIMHelper filterMessage:msg.text];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [converses removeObject:_serviceCov];
            strongSelf.serviceView.con = _serviceCov;
            [_converseView reloadData:converses];
        });
    });
}

/**
 *  @author zhengrs, 16-01-07 10:01:31
 *
 *  @brief 被从群组踢除
 *
 *  @param group
 */
-(void)didReceiveBeBanFromGroup:(TKIMRoom *)group
{
    NSMutableArray *array = [[TKIMManager shareInstance] queryHisConverses];
    [self didReceiveConverse:array];
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"您已被从群组“%@”中移出",group.roomName] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    
}
/**
 *  @author zhengrs, 16-01-07 10:01:31
 *
 *  @brief 群组解散群
 *
 *  @param group
 */
-(void)didReceiveGroupDestroy:(TKIMRoom *)group
{
    NSMutableArray *array = [[TKIMManager shareInstance] queryHisConverses];
    [self didReceiveConverse:array];
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"群组“%@”已被解散",group.roomName] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
}


#pragma mark 工具方法

/**
 *  @Author lpm, 15-11-06 17:11:46
 *
 *  @brief  设置未读消息数
 *
 *  @param converses
 */
-(void)setTabBarBadgeValue:(NSMutableArray *)converses
{
    NSInteger count = 0;
    for (TKIMConverseMessage *msg in converses)
    {
        count += msg.msgCount;
    }
    if (count == 0)
    {
        self.navigationController.tabBarItem.badgeValue = nil;
    }
    else
    {
//        self.navigationController.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",(long)count];
    }
}

/**
 *  @Author lpm, 15-11-05 12:11:22
 *
 *  @brief
 *
 *  @param user
 */
-(void)toChat:(TKIMUser *)user converse:(TKIMConverseMessage *)cover
{
    BOOL isNeedSendState=false;
    if (cover) {
        if (cover.msgCount>0) {
            isNeedSendState=true;
        }
    }
    //这里区分哪些是需要倒序的哪些死不需要倒序的
    
    if (cover.channel==2) {
        TKIMSMSChatViewController *chat = [[TKIMSMSChatViewController alloc] init];
        chat.user = user;
        chat.isNeedSetState=isNeedSendState;
        [chat setHidesBottomBarWhenPushed:YES];
        [self.navigationController pushViewController:chat animated:YES];
    
    }else{
        if (cover.isNeedOtherManage) {//需要第三方处理
            
        }else{
           BOOL iskefu=false;
           if (cover.channel==1) {
              iskefu = true;

               NSString *tkConverseUrl = [TKIMSDKConfig shareInstance].tkConverseUrl;
               NSString *postURL = tkConverseUrl;
//               if([TKIMCacheHelper boolForKey:SDK_IS_BIND_USER]){ // 登录
//
//                   postURL = [NSString stringWithFormat:@"%@?app_key=AiZFT&zjzh=%@", tkConverseUrl, [TKIMCacheHelper valueForKey:SDK_LOGINUSER_USERNAME]];
//               }else{ // 未登录
//
//                   postURL = [NSString stringWithFormat:@"%@?app_key=AiZFT&openid=%@", tkConverseUrl, [TKIMSDKManager imUDID]];
//               }

               NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
               [dict setValue:postURL forKey:TKIMSDK_CS_URL];
               [[NSNotificationCenter defaultCenter] postNotificationName:TKIMSDK_OPEN_NEW_CUSTOMER_SERVICE object:dict];

               return;
           }
           TKIMChatViewController *chat = [[TKIMChatViewController alloc] init];
           chat.user = user;
            [[TKIMManager shareInstance] resetUserConverseCount:user.userID];
           chat.isKeFu=iskefu;
           chat.channel = cover.channel;
           [chat setHidesBottomBarWhenPushed:YES];
           [self.navigationController pushViewController:chat animated:YES];
        }
    }
}


-(void)dealloc
{
    [[TKIMManager shareInstance] unRegisterDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark --懒加载
-(TKIMConverseServiceView*)serviceView
{
    if (!_serviceView) {
        _serviceView = [[TKIMConverseServiceView alloc] initWithFrame:CGRectMake(0,CGRectGetMaxY(self.converseView.frame), self.view.width, 76)];
        [_serviceView.actionBtn addTarget:self action:@selector(actionBtnClick) forControlEvents:UIControlEventTouchUpInside];
        _serviceView.delegate = self;
    }
    return _serviceView;
}


#pragma mark --界面事件
-(void)actionBtnClick
{
    TKIMUser *user = [[TKIMUser alloc] init];
    user.userID = _serviceCov.targetUser;
    user.nickName = _serviceCov.targetUserName;
    user.isToTop = _serviceCov.isToTop;
    user.userType = _serviceCov.chatUserType;
    [self toChat:user converse:_serviceCov];
}


@end
